//
//  SearchView.m
//  AriseSamePro
//
//  Created by 包日守 on 15/10/26.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "SearchView.h"
#import "SelectTableVew.h"
#import "ARGlobalInterface.h"
#import "AFNetworking.h"
#import "ZJModelTool.h"
#import "ARSearchModel.h"
#import "ChannelCell.h"
#import "UIImageView+AFNetworking.h"
#import "SearchNoFindCell.h"
#import "ChannelTableViewController.h"

@interface SearchView ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *serachBar;
@property (weak, nonatomic) IBOutlet UIButton *allButton;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UITextField *textFiled;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *hightConstraint;
@property (weak, nonatomic) SelectTableVew *selectTableView;

@property (nonatomic) NSArray *dataArray;

@property (weak, nonatomic) IBOutlet UITableView *searchtableView;

@property (weak, nonatomic) IBOutlet UIImageView *scanImageView;

@property (weak, nonatomic) IBOutlet UILabel *scanLabel;



@property (nonatomic) BOOL isEmpty;

@property (weak, nonatomic) IBOutlet UIImageView *moreButtonImage;

@end

@implementation SearchView


- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
    if (_dataArray.count == 0) {
        self.scanLabel.hidden = NO;
        self.scanImageView.hidden = NO;
        self.isEmpty = YES;
    }
    else
    {
        self.scanLabel.hidden = YES;
        self.scanImageView.hidden = YES;
        self.isEmpty = NO;
    
    }
}


- (void) loadDataInServer
{
    [self finish];
    if([self.textFiled.text isEqualToString: @""])
        return;
    
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    NSString *url = [ARGlobalInterface searchWithCate:self.selectTableView.cate WithKey:self.textFiled.text];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        
        
        NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        NSMutableArray *marray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            
            ARSearchModel *model = [[ARSearchModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [marray addObject:model];
            
        }
        
        self.dataArray = marray;
        [self.searchtableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];



}


- (IBAction)selectButtonClick:(id)sender {

    UIButton *button = (UIButton *) sender;
    
    button.selected = ! button.selected;
    
    if (button.selected) {
        
        
        
        
        [self.textFiled resignFirstResponder];
        [UIView animateWithDuration:0.5 animations:^{
            self.selectTableView .frame = CGRectMake(0, 20 + 44, [UIScreen mainScreen].bounds.size.width, 44*8);
            self.moreButtonImage.transform =  CGAffineTransformMakeScale(1, -1);
        }];
    }
    else
    {
        [self finish];
    
    }
}


- (void) finish
{
    [self.textFiled resignFirstResponder];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.selectTableView .frame = CGRectMake(0, 20 +44, [UIScreen mainScreen].bounds.size.width, 0);
    }];
    
    self.moreButtonImage.transform =  CGAffineTransformMakeScale(1, 1);

}


- (void) removeFromSuperview
{
    [super removeFromSuperview];
}

- (IBAction)cancelButtonClick:(id)sender {
    [self removeFromSuperview];
    
    if (self.delegate) {
        [self.delegate searchViewControllerBACK];
    }
    
    
    
}
- (void) awakeFromNib
{
    self.isEmpty = NO;
    
    self.serachBar.layer.cornerRadius = 10;
    //self.tintColor = [UIColor whiteColor];
    //self.blurRadius = 10;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    [self.textFiled becomeFirstResponder];
    
   // UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dealSwipe:)];
    //默认: 从左到右滑动生效
   // swipe.direction = UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown;
    //[self.searchtableView addGestureRecognizer:swipe];
    
    
    CGRect rect = [UIScreen mainScreen].bounds;
    
    
    SelectTableVew *selectTableView = [[SelectTableVew alloc] initWithFrame:CGRectMake(0, 20 + 44 , rect.size.width,0) style:UITableViewStylePlain];
    
    [self addSubview:selectTableView];
    self.selectTableView = selectTableView;
    
    [selectTableView setSelectButtonClick:^{
        [self.textFiled resignFirstResponder];
        [self loadDataInServer];
        
        [self.allButton setTitle:self.selectTableView.title forState:UIControlStateNormal];
        
        [UIView animateWithDuration:0.5 animations:^{
            self.selectTableView .frame = CGRectMake(0, 20 + 44, [UIScreen mainScreen].bounds.size.width, 0);
        }];
        
    }];
    
    //[self sendSubviewToBack:self.selectTableView];
    
    self.textFiled.delegate = self;
    
    
    [self.searchtableView registerNib:[UINib nibWithNibName:@"ChannelCell" bundle:nil] forCellReuseIdentifier:@"ChannelCellID"];
    
    
    
    [self.searchtableView registerNib:[UINib nibWithNibName:@"SearchNoFindCell" bundle:nil] forCellReuseIdentifier:@"NotFindCellID"];
    
    UITapGestureRecognizer *tapScanV = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onScanButton)];
    [self.scanImageView addGestureRecognizer:tapScanV];
    self.scanImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapScanL = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onScanButton)];
    [self.scanLabel addGestureRecognizer:tapScanL];
    self.scanLabel.userInteractionEnabled = YES;
    
}

- (void) onScanButton
{
    NSLog(@"open SCAN");
    
    
    if (self.delegate) {
        [self.delegate scanViewControllerIN];
    }

}



- (void)keyBoardWillShow:(NSNotification *) notify
{
    [self updateKeyBoardStatus:notify show:YES];
    
}

- (void)keyBoardWillHide:(NSNotification *) notify
{
    [self updateKeyBoardStatus:notify show:NO];
    
}


- (void) updateKeyBoardStatus: (NSNotification *) notify show: (BOOL) isShow
{
    
    NSDictionary * userInfo = [notify userInfo];
    
    NSTimeInterval animationDuration ;
    
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    
    CGRect kbFrame;
    
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&kbFrame];
    
 
    self.hightConstraint.constant = isShow?CGRectGetHeight(kbFrame)  + 10: 40;
    

    [UIView animateWithDuration:animationDuration animations:^{
        [self layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
    
    
}
#pragma mark -textFileDelegate
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textFiled resignFirstResponder];
    [self loadDataInServer];
    return YES;

}

#pragma mark - tableViewDelegate


- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isEmpty == YES) {
        NSLog(@"create new channel");
    }
    else
    {
        
        ARSearchModel *model = self.dataArray[indexPath.row];
        
        if (self.delegate) {
            [self.delegate searchViewcontrollerINWithIndex:model.index WithCate:model.cate WithTitle:model.name];
        }
    
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isEmpty == YES) {
        return 1;
    }
    
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.isEmpty == YES) {
        
        SearchNoFindCell *cell = [self.searchtableView dequeueReusableCellWithIdentifier:@"NotFindCellID"];
        
        
        cell.titleLabel.text = [NSString stringWithFormat:@"没有找到\"%@\"?",self.textFiled.text];
        
        
        return cell;
    }
    
    
    ARSearchModel *model = self.dataArray[indexPath.row];
    
    ChannelCell *cell = [self.searchtableView dequeueReusableCellWithIdentifier:@"ChannelCellID"];
    
    cell.titleLabel.text = model.name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"已产生%@条内容",model.times];
    [cell.iconImageView setImageWithURL:[NSURL URLWithString:model.icon]];
    [cell.cateImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"type_icon%@.png",model.cate]]];
    
    return cell;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
#pragma mark - scrollVeiwdelegate
 - (void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    
    [self finish];

}


@end
